<template>
  <div
    class="dashboard"
    v-loading="loading"
    element-loading-text="数据加载中..."
    element-loading-background="rgba(255, 255, 255, 0.9)"
    element-loading-svg-view-box="-10, -10, 50, 50"
    :element-loading-svg="svg"
  >
    <AssetOverview
      :data="dashboardData.assetOverview"
      :rental-data="dashboardData.rentalData"
      :contract-data="dashboardData.contractData"
      :vacancy-data="dashboardData.vacancyData"
    />
    <!-- <div class="chart-row">
      <WarningTrend class="chart-item" :data="dashboardData.warningTrend" />
      <WarningAssetList
        class="chart-item"
        :data="dashboardData.warningAssetList"
      />
    </div> -->
    <div style="width: 100%; display: flex; justify-content: space-between">
      <div style="width: 40%; height: 400px">
        <EChartsComponent
          :xAxisData="['1', '2', '3', '4', '5', '6', '7']"
          :seriesData="lineSeriesData"
        />
      </div>
      <div style="width: 40%; height: 400px">
        <EChartsComponent
          :xAxisData="['1', '2', '3', '4', '5', '6', '7']"
          :seriesData="barSeriesData"
        />
      </div>
    </div>
    <div style="width: 100%; display: flex; justify-content: space-between">
      <div style="width: 40%; height: 400px">
        <EChartsComponent
          :direction="true"
          :xAxisData="['1', '2', '3', '4', '5', '6', '7']"
          :seriesData="barDireSeriesData"
        />
      </div>
      <div style="width: 40%; height: 400px">
        <PieComponent :seriesData="pieSeriesData" />
      </div>
    </div>
    <div>
      <PieProgress :value="30" :total="100" color="#09f" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import AssetOverview from "./components/AssetOverview.vue";
import WarningTrend from "./components/WarningTrend.vue";
import WarningAssetList from "./components/WarningAssetList.vue";
import EChartsComponent from "@/components/echarts/lineBar.vue";
import PieComponent from "@/components/echarts/pie1.vue";
import PieProgress from "@/components/echarts/pie2.vue";
import {
  getAssetOverview,
  getSpecAssetList,
  getWarningTrends,
} from "./services";

const loading = ref(true);
const dashboardData = ref({
  // 资产概览数据 - 所有数值默认为0
  assetOverview: {
    totalAssets: 0,
    vacantRate: "0%",
    rentalPriceCount: 0,
    contractCount: 0,
    emptyMonitorCount: 0,
    noContractRate: "0%",
    vacantTotal: 0,
  },
  // 三个图表的数据
  rentalData: [], // 租金价格预警数据
  contractData: [], // 合同合规预警数据
  vacancyData: [], // 空置监测预警数据
  // 预警趋势数据 - 暂无数据
  warningTrend: {
    dates: [],
    series: [],
  },
  // 预警资产列表 - 暂无数据
  warningAssetList: [],
  // 空置分布数据 - 暂无数据
  vacancyDistribution: [],
});

const lineSeriesData = computed(() => {
  return [
    {
      name: "Email",
      type: "line",
      stack: "Total",
      smooth: true,
      symbol: "none",
      data: [120, 132, 101, 134, 90, 230, 210],
    },
    {
      name: "Union Ads",
      type: "line",
      stack: "Total",
      smooth: true,
      data: [220, 182, 191, 234, 290, 330, 310],
    },
    {
      name: "Video Ads",
      type: "line",
      stack: "Total",
      smooth: true,
      data: [150, 232, 201, 154, 190, 330, 410],
    },
    {
      name: "Direct",
      type: "line",
      stack: "Total",
      smooth: true,
      data: [320, 332, 301, 334, 390, 330, 320],
    },
    {
      name: "Search Engine",
      type: "line",
      stack: "Total",
      smooth: true,
      data: [820, 932, 901, 934, 1290, 1330, 1320],
    },
  ];
});
const barSeriesData = computed(() => {
  return [
    {
      name: "督办工单数",
      type: "bar",
      data: [10, 52, 200, 334, 390, 330, 220],
    },
  ];
});
const barDireSeriesData = computed(() => {
  return [
    {
      name: "Direct",
      type: "bar",
      stack: "total",
      label: {
        show: true,
      },
      emphasis: {
        focus: "series",
      },
      data: [320, 302, 301, 334, 390, 330, 320],
    },
    {
      name: "Mail Ad",
      type: "bar",
      stack: "total",
      label: {
        show: true,
      },
      emphasis: {
        focus: "series",
      },
      data: [120, 132, 101, 134, 90, 230, 210],
    },
    {
      name: "Affiliate Ad",
      type: "bar",
      stack: "total",
      label: {
        show: true,
      },
      emphasis: {
        focus: "series",
      },
      data: [220, 182, 191, 234, 290, 330, 310],
    },
    {
      name: "Video Ad",
      type: "bar",
      stack: "total",
      label: {
        show: true,
      },
      emphasis: {
        focus: "series",
      },
      data: [150, 212, 201, 154, 190, 330, 410],
    },
    {
      name: "Search Engine",
      type: "bar",
      stack: "total",
      label: {
        show: true,
      },
      emphasis: {
        focus: "series",
      },
      data: [820, 832, 901, 934, 1290, 1330, 1320],
    },
  ];
});
const pieSeriesData = computed(() => {
  return [
    { name: "噪音", value: 44 },
    { name: "卫生", value: 24 },
    { name: "食品安全", value: 20 },
    { name: "划痕", value: 12 },
    { name: "证件", value: 11 },
    { name: "其他", value: 11 },
  ];
});
// 自定义loading图标
const svg = `
  <path class="path" d="
    M 30 15
    L 28 17
    M 25.61 25.61
    A 15 15, 0, 0, 1, 15 30
    A 15 15, 0, 1, 1, 27.99 7.5
    L 15 15
  " style="stroke-width: 4px; fill: none"/>
`;

const fetchData = async () => {
  try {
    loading.value = true;
    // 获取概览数据
    const overviewData = await getAssetOverview();
    // 获取特殊资产列表
    const specAssetData = await getSpecAssetList();

    // 获取三种类型的预警趋势数据
    const [rentalTrend, contractTrend, vacancyTrend] = await Promise.all([
      getWarningTrends("租金价格"),
      getWarningTrends("合同合规"),
      getWarningTrends("空置"),
    ]);

    // 获取预警趋势数据
    const warningTrendData = await getWarningTrends();

    // 分别处理三种预警数据
    const rentalData = (rentalTrend?.data || []).map((item) => ({
      date: item.date || item.month,
      count: item.count,
    }));

    const contractData = (contractTrend?.data || []).map((item) => ({
      date: item.date || item.month,
      count: item.count,
    }));

    const vacancyData = (vacancyTrend?.data || []).map((item) => ({
      date: item.date || item.month,
      count: item.count,
    }));

    // 处理预警趋势数据
    const processWarningTrendData = (data) => {
      // 获取所有日期
      const allDates = [
        ...new Set(data.map((item) => item.date || item.month)),
      ].sort();

      // 按预警类型分组数据
      const groupedData = {
        租金价格: [],
        合同合规: [],
        空置: [],
        无合同: [],
      };

      // 初始化每个类型的数据数组
      Object.keys(groupedData).forEach((type) => {
        groupedData[type] = allDates.map((date) => {
          const item = data.find(
            (d) => (d.date || d.month) === date && d.warning_type === type
          );
          return item ? item.count : 0;
        });
      });

      return {
        dates: allDates,
        series: [
          {
            name: "租金比对预警",
            data: groupedData["租金价格"],
            type: "line",
            yAxisIndex: 0,
          },
          {
            name: "合同合规预警",
            data: groupedData["合同合规"],
            type: "line",
            yAxisIndex: 0,
          },
          {
            name: "空置监测预警",
            data: groupedData["空置"],
            type: "line",
            yAxisIndex: 0,
          },
          {
            name: "无合同",
            data: groupedData["无合同"],
            type: "line",
            yAxisIndex: 1,
          },
        ],
      };
    };

    // 更新各个模块的数据
    dashboardData.value = {
      assetOverview: {
        ...(overviewData?.data || {
          totalAssets: 0,
          vacantRate: "0%",
          rentalPriceCount: 0,
          contractCount: 0,
          emptyMonitorCount: 0,
          noContractRate: "0%",
          vacantTotal: 0,
        }),
      },
      // 分别赋值三个图表的数据到顶层
      rentalData,
      contractData,
      vacancyData,
      warningAssetList: specAssetData?.rows || [],
      warningTrend: processWarningTrendData(warningTrendData?.data || []),
      vacancyDistribution: [],
    };

    console.log("Dashboard data=====:", dashboardData.value);
  } catch (error) {
    console.error("Failed to fetch dashboard data:", error);
    // 发生错误时重置数据
    dashboardData.value.rentalData = [];
    dashboardData.value.contractData = [];
    dashboardData.value.vacancyData = [];
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchData();
});
</script>

<style lang="scss" scoped>
.dashboard {
  padding: 24px;
  background: #f5f7fa;
  min-height: 90vh;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 24px;

  .chart-row {
    display: flex;
    gap: 24px;
    height: calc(100vh - 290px);
    min-height: 400px;

    .chart-item {
      flex: 1;
      min-width: 0;
      background: #fff;
      border-radius: 8px;
      // padding: 20px;
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    }
  }

  :deep(.chart-container) {
    width: 100%;
    height: 100% !important;
  }

  // 自定义loading样式
  :deep(.el-loading-spinner) {
    .path {
      stroke: var(--el-color-primary);
      stroke-linecap: round;
      animation: dash 1.5s ease-in-out infinite;
    }

    .el-loading-text {
      color: var(--el-color-primary);
      font-size: 16px;
      margin: 3px 0;
    }
  }
}

@keyframes dash {
  0% {
    stroke-dasharray: 1, 150;
    stroke-dashoffset: 0;
  }
  50% {
    stroke-dasharray: 90, 150;
    stroke-dashoffset: -35;
  }
  100% {
    stroke-dasharray: 90, 150;
    stroke-dashoffset: -124;
  }
}
</style>
